<template>
  <el-select
    v-model="value"
    filterable
    remote
    :remote-method="remoteMethod"
    :loading="roles.pending.value"
    v-bind="$attrs"
    remote-show-suffix
    @visible-change="onVisibleChange"
  >
    <el-option
      v-for="item in roles.data.value?.list"
      :key="item.key"
      :label="item.title"
      :value="item.key"
    />
  </el-select>
</template>

<script setup lang="ts">
import { Status } from '~~/types/status.d';

import { PageData } from '~~/types/pageData.d';
import { Role } from '~~/types/role.d';
import { AsyncData } from '#app';

interface Props {
  // multiple: boolean;
  modelValue?: string | string[];
}

const props = defineProps<Props>();
const emit = defineEmits(['update:modelValue']);

const value = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  },
});

// interface ListItem {
//   value: string;
//   label: string;
// }

// const options = ref<ListItem[]>([]);

const query = ref({
  page: 1,
  pageSize: 1,
  title: '',
  key: <string[] | string | undefined>[],
});

// 监听初始值，并初始化下拉列表，用于显示正确的title
const { stop } = watchPausable(
  toRef(props, 'modelValue'),
  (value) => {
    const key = useCloned(value).cloned.value;
    console.log('🚀 ~ file: role-select.vue:65 ~ key:', key);
    query.value.key = key;
    query.value.pageSize = Array.isArray(key) ? key.length : key ? 1 : 0;
  },
  {
    // immediate: true,
  },
);

const roles = useFetchApi('/system/role', {
  query,
  default: () =>
    <PageData<Role>>{
      list: [],
      total: 0,
    },
  immediate: true,
});

function remoteMethod(value: string) {
  // console.log('🚀 ~ file: role-select.vue:65 ~ remoteMethod ~ value:', value);
  query.value.pageSize = 10;
  query.value.key = [];
  query.value.title = value;
  console.log(query.value);
}

function onVisibleChange(val: boolean) {
  if (val) {
    query.value.pageSize = 10;
    query.value.key = [];
    query.value.title = '';
    // 在打开下拉框后停止初始值监听器，
    stop();
  }
}

// const initRoles = await useFetchApi('/system/role', {
//   query: {
//     page: 1,
//     pageSize: value.value.length || 10,
//     key: value.value,
//   },
//   default: () =>
//     <PageData<Role>>{
//       list: [],
//       total: 0,
//     },
//   immediate: true,
// });
// roles.data.value = initRoles.data.value;
</script>

<style scoped></style>
